<template>
  <div class="app-container">
    <el-row>总预期工作量:{{sum}}人日.(默认初始化工作大纲,请根据需要添加工作事项)</el-row>
    <qm-table
      ref="qmTable"
      keyProp="menuId"
      :data="{ data: menuData }"
      :showOrder="false"
      :showPager="false"
      menuType="text"
      :menuOptions="{ width: 180 }"
      :formOptions="{ labelWidth: '150px' }"
      :options="{
        rowId: 'menuId',
        border: false,
        treeConfig: {trigger: 'cell', reserve: true,iconOpen: 'fa fa-minus-square-o', iconClose: 'fa fa-plus-square-o'}
      }"
      :rules="rules"
      :showView="false"
      :showCheckbox="false"
      refreshType="none"
      :refreshFunc="treeRefresh"
      :removeFunc="removeRow"
      :textMap="{ add: '添加工作大纲' }"
      :showMenu="false"
      :showAdd="status!='close'"
    >
      <qm-table-column width="200px" field="text" tree-node>
        工作大纲
        <template v-slot:content="{ row }">
          <span>
            <template v-if="row.children">
              <i
                class="tree-node-icon fa"
                :class="
                  $refs.qmTable.isTreeExpandByRow(row)
                    ? 'fa fa-list-ol'
                    : 'fa fa-file-text'
                "
              ></i>
            </template>
            <template v-else>
              <i class="tree-node-icon fa fa-file-text"></i>
            </template>
            <span>{{ row.text }}</span>
          </span>
        </template>
      </qm-table-column>
      <qm-table-column field="plan" width="200px">工作事项</qm-table-column>
      <qm-table-column field="expectedWorkload" width="150px">预期工作量</qm-table-column>
      <qm-table-column field="expectedDate" width="120px">预期完成日期</qm-table-column>
      <qm-table-column field="sort" width="120px">排序</qm-table-column>
      <qm-table-column field="description" show-overflow>备注</qm-table-column>

      <template v-slot:moreBtn="{ row }">
        <el-button type="text" v-if="row.menuId" @click="addSubMenu(row)">添加</el-button>
      </template>

      <vxe-column v-if="status!='close'" width="300px" title="操作">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            v-if="row.parentId==null"
            icon="el-icon-plus"
            @click="viewInfo(row)"
          >添加工作事项</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="showEditModal(row)">编辑</el-button>
          <el-button
            v-if="row.parentId!=null"
            type="danger"
            icon="el-icon-delete"
            @click="remove(row)"
          >删除</el-button>
        </template>
      </vxe-column>

      <template v-slot:form="{ model }">
        <el-row>
          <el-col :span="24">
            <el-form-item hidden label="上级目录：" prop="model.parentId">
              <treeselect
                v-model="model.parentId"
                :options="menuData"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="根目录"
                noChildrenText="没有了"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="model.parentId==null" label="工作大纲：" prop="model.name">
              <el-input v-model="model.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="model.parentId!=null" label="工作事项：" prop="model.plan">
              <el-input v-model="model.plan"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号：" prop="model.sort">
              <el-input v-model.number="model.sort"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预期工作量：" prop="model.expectedWorkload">
              <el-input v-model.number="model.expectedWorkload">
                <template slot="append">人日</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预期完成日期：" prop="model.expectedDate">
              <el-date-picker
                v-model="model.expectedDate"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="model.description">
              <el-input
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 8}"
                v-model="model.description"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </qm-table>
  </div>
</template>

<script>
import Controller from "@/libs/framework/controller";
import request from "@/utils/request";
import _ from "lodash";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      model: "/eip/Outline/getListModel",
      save: "/eip/Outline/save",
      delete: "/eip/Outline/delete",
      entity: "/eip/Outline/getEntity",
    };
  }
  onAfterGetEntity(result) {
    if (
      result &&
      result.models &&
      result.models.model &&
      result.pageAction === "create"
    ) {
      result.models.model.parentId = this.vm.parentId || undefined;
      this.vm.parentId = undefined;
    }
  }

  onBeforeSave(postModel) {
    if (postModel.pageAction === "create") {
      postModel.model.projectId = this.vm.projectId;
    }
    if (postModel.model.parentId === undefined) {
      postModel.model.parentId = null;
    }
    return true;
  }

  mixin() {
    return {
      components: {
        Treeselect,
      },
      data() {
        return {
          status: null,
          sum: 0.0,
          projectId: null,
          modalVisible: false,
          dialogVisible: false,
          parentId: "",
          menuData: [],
          treeData: [],
          rules: {
            model: {
              name: [
                {
                  required: true,
                  message: "请选择工作大纲",
                  trigger: "blur",
                },
              ],
              plan: [
                {
                  required: true,
                  message: "请输入工作事项",
                  trigger: "blur",
                },
              ],
              expectedWorkload: [
                {
                  required: true,
                  message: "请填写预期工作量",
                  trigger: "blur",
                },
              ],
              expectedDate: [
                {
                  required: true,
                  message: "请选择预期完成日期",
                  trigger: "blur",
                },
              ],
            },
          },
        };
      },
      methods: {
        normalizer(node) {
          return {
            id: node.id,
            label: node.text,
            children: node.children,
          };
        },
        addSubMenu(row) {
          this.parentId = row.menuId;
          this.$refs["qmTable"].addNew();
        },
        removeRow(rows) {
          let row = rows && rows.length ? rows[0] : {};
          let parent = this.$refs["qmTable"].getRowById(row.parentId);
          const menuId = row.menuId;
          const url = this.urls.delete || this.urls.remove;

          if (url === undefined || menuId === undefined) {
            this.$message({
              showClose: true,
              message: "PostModel或者URL不可为undefined",
              type: "error",
            });
          } else {
            this.$confirm("确定删除吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                let loading = this.appLoading("正在删除...");
                request({
                  url: url,
                  method: "post",
                  data: {
                    delete: JSON.stringify([{ menuId: menuId }]),
                  },
                })
                  .then((res) => {
                    if (res && res.success) {
                      this.$message({
                        showClose: true,
                        message: res.message || "删除成功！",
                        type: "success",
                      });
                      this.treeRefresh();
                      // // 从数据源删除该行即可，不需要重新加载整棵树
                      // if (parent && parent.children) {
                      //   parent.children.remove(row);
                      // } else {
                      //   // 删除的是顶级的菜单
                      //   this.menuData.remove(row);
                      // }
                    } else {
                      this.$message({
                        showClose: true,
                        message: res ? res.message : undefined || "删除失败！",
                        type: "error",
                      });
                    }
                  })
                  .catch((err) => {
                    this.$message({
                      showClose: true,
                      message: err.message || "删除失败！",
                      type: "error",
                    });
                  })
                  .finally(() => {
                    loading.close();
                  });
              })
              .catch();
          }
        },
        treeRefresh(params) {
          this.getAllTreeData(this.projectId);
        },
        getAllTreeData(projectId) {
          request({
            url: "/eip/Outline/getAllMenuData",
            method: "post",
            data: { projectId: projectId },
          })
            .then((r) => {
              if (r && r.parameters && r.parameters.treeData) {
                this.menuData = this.handleTree(r.parameters.treeData);
                this.sum = r.parameters.sum;
              }
            })
            .catch((e) => {
              this.msgError("获取数据失败，请稍后再试");
            });
        },
        handleTree(treeData) {
          let arr = [];
          _.each(treeData, (item) => {
            let m = {};
            m.id = item.id;
            m.menuId = item.id;
            m.text = item.text;
            m.parentId = item.data.parentId;
            m.description = item.data.description;
            m.expectedDate = item.data.expectedDate;
            m.expectedWorkload = item.data.expectedWorkload + "人日";
            m.sort = item.data.sort;
            m.plan = item.data.plan;
            if (item.children && item.children.length) {
              m.children = this.handleTree(item.children) || [];
            } else {
              m.children = [];
            }
            arr.push(m);
          });
          return arr;
        },
        loadChildrenMethod({ row }) {
          // 异步加载子节点
          return new Promise((resolve) => {
            request({
              url: "/admin/sysMenu/getChild",
              method: "get",
              params: { id: row.id },
            })
              .then((r) => {
                r.forEach((item) => {
                  if (item.children) {
                    item.childs = [];
                  }
                  if (item.id !== "root") {
                    item.menuId = item.id;
                  }
                });
                resolve(r);
              })
              .catch((e) => {
                this.msgError("获取数据失败，请稍后再试");
              });
          });
        },
        viewInfo(row) {
          this.addSubMenu(row);
        },
        showEditModal(row) {
          this.$refs["qmTable"].showEditModal(row);
        },
        remove(row) {
          this.$refs["qmTable"].remove(row);
        },
      },
      created() {
        this.projectId = this.$attrs.projectId;
        this.status = this.$attrs.status;
        this.getAllTreeData(this.projectId);
      },
    };
  }
}
</script>

<style scoped lang="scss"></style>
